Hi guys!
It’s really amazing what you can do within the R environment and one of the main desires of those who work with R is to make beautiful graphics. I speak for myself! For that, ggplot2 is an essential package for those who like to make beautiful graphics. But did you know that you can do more? Yes! You can create an interactive chart with any ggplot chart using the plotly package. Want to learn how to do? Then come with me!
First, let’s start loading the necessary packages. We will use the gapminder package to obtain a database for our class.
library(ggplot2)
library(plotly)
library(gapminder)
Now let’s create our dataframe and visualize it.
df <- gapminder
df
## # A tibble: 1,704 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
## 7 Afghanistan Asia 1982 39.9 12881816 978.
## 8 Afghanistan Asia 1987 40.8 13867957 852.
## 9 Afghanistan Asia 1992 41.7 16317921 649.
## 10 Afghanistan Asia 1997 41.8 22227415 635.
## # ... with 1,694 more rows
These Gapminder data are about life expectancy, GDP per capita and population by country, comprising several years. To facilitate our visualization in the graph, we will filter only the year 1992.
df = df%>%
filter(year==1992)
df
## # A tibble: 142 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1992 41.7 16317921 649.
## 2 Albania Europe 1992 71.6 3326498 2497.
## 3 Algeria Africa 1992 67.7 26298373 5023.
## 4 Angola Africa 1992 40.6 8735988 2628.
## 5 Argentina Americas 1992 71.9 33958947 9308.
## 6 Australia Oceania 1992 77.6 17481977 23425.
## 7 Austria Europe 1992 76.0 7914969 27042.
## 8 Bahrain Asia 1992 72.6 529491 19036.
## 9 Bangladesh Asia 1992 56.0 113704579 838.
## 10 Belgium Europe 1992 76.5 10045622 25576.
## # ... with 132 more rows
Now our data is ready to be plotted. Let’s create a beautiful dot plot in ggplot using data from GDP per capita, life expectancy, population and continent.
ggplot(df, aes(gdpPercap, lifeExp, size = pop, color=continent)) +
geom_point() +
theme_bw()
Ok … the graph was beautiful, but so what? How to make it interactive?
This is the easiest part of all! We will simply put the graph we created inside an object and load it using the ggplotly function.
gg = ggplot(df, aes(gdpPercap, lifeExp, size = pop, color=continent)) +
geom_point() +
theme_bw()
ggplotly(gg)
Of course, there are many more functions and possibilities using the plotly package. To learn more read the package documentation and visit the plotly website (https://plotly.com/).
Make good use of this information!